import router from './index'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getLonglivedToken, getToken } from '@/utils/Auth.ts'
import store from '@/store'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login']

router.beforeEach((to, _, next) => {
  NProgress.start()

  if (to.path === '/logout') {
    store.dispatch('user/logout').then(() => {
      next('/login')
      NProgress.done()
    })
    return
  }

  const token = getToken()
  const longlivedToken = getLonglivedToken()
  if (token && longlivedToken) {
    if (to.path === '/login') next({ path: '/' })
    else next()
  } else {
    if (whiteList.includes(to.path)) next()
    else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
